package com.hxzy.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.vo.AccountVO;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import org.mybatis.spring.annotation.MapperScan;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置mybatis其它插件
 *
 * @author Administrator
 */
@Configuration
@MapperScan(basePackages = "com.hxzy.mapper")
public class MybatisConfig {

    //private String ignoreTables="address_book,contamer,dish_flavor,employee,merchandiser,shopping_cart";

    @Value(value = "${ignore.tables}")
    private String[] ignoreTables;

    /**
     * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {

        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {

            /**
             * 配置多租户数据库列名
             * @return
             */
            @Override
            public String getTenantIdColumn() {
                return "merchant_id";
            }

            @Override
            public Expression getTenantId() {
                AccountVO accountVO = WaimaiThreadLocal.getCurrent().getAccountVO();
                return new LongValue(accountVO.getId());
            }

            // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
            @Override
            public boolean ignoreTable(String tableName) {
                boolean ignore = false;
                //如果未登录，多租户无效
                if(WaimaiThreadLocal.getCurrent()==null){
                   return true;
                }

                // 如果当前tableName与配置的ignoreTables 相等，就不要根据商家id查询
                if (ignoreTables != null && ignoreTables.length > 0) {
                    for (String name : ignoreTables) {
                        if (name.equalsIgnoreCase(tableName)) {
                            ignore = true;
                            break;
                        }
                    }
                }

                return ignore;
            }
        }));
        return interceptor;
    }
}
